package com.shm.leetcode;

import java.util.*;

/**
 * @author: shm
 * @dateTime: 2020/9/29 9:52
 * @description: 145. 二叉树的后序遍历
 * 给定一个二叉树，返回它的 后序 遍历。
 *
 * 示例:
 *
 * 输入: [1,null,2,3]
 *    1
 *     \
 *      2
 *     /
 *    3
 *
 * 输出: [3,2,1]
 * 进阶: 递归算法很简单，你可以通过迭代算法完成吗？
 */
public class PostorderTraversal {

    List<Integer> res = new ArrayList<>();
    public List<Integer> postorderTraversal(TreeNode root) {
        if (root==null){
            return res;
        }

        if (root.left!=null) {
            postorderTraversal(root.left);
        }
        if (root.right!=null) {
            postorderTraversal(root.right);
        }
        res.add(root.val);
        return res;
    }


    public List<Integer> postorderTraversal_2(TreeNode root) {
        if (root==null){
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        while (root!=null||!stack.isEmpty()){
            while (root!=null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right==null||root.right==pre){
                res.add(root.val);
                pre = root;
                root = null;
            }else {
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }

    public List<Integer> postorderTraversal_3(TreeNode root) {
        Deque<TreeNode> deque = new LinkedList<>();
        LinkedList<Integer> ans = new LinkedList<>();
        if (root==null){
            return ans;
        }
        deque.addFirst(root);
        while (!deque.isEmpty()){
            TreeNode node = deque.removeFirst();
            ans.addFirst(node.val);
            if (node.left!=null){
                deque.addFirst(node.left);
            }
            if (node.right!=null){
                deque.addFirst(node.right);
            }
        }
        return ans;
    }

    public List<Integer> postorderTraversal_4(TreeNode root) {
        Deque<TreeNode> deque = new LinkedList<>();
        LinkedList<Integer> ans = new LinkedList<>();
        if (root==null){
            return ans;
        }
        deque.push(root);
        while (!deque.isEmpty()){
            TreeNode node = deque.removeFirst();
            ans.addFirst(node.val);
            if (node.left!=null){
                deque.push(node.left);
            }
            if (node.right!=null){
                deque.push(node.right);
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        PostorderTraversal postorderTraversal = new PostorderTraversal();
        postorderTraversal.postorderTraversal_4(root);
    }
}
